package br.com.android.rtgym.services;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import br.com.android.rtgym.beans.Treino;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


public class TreinosUsuario {
	
private String path = "";
	
	public TreinosUsuario() {
		super();
	}
	
	public TreinosUsuario(String path) {
		this.path = path;
	}
	
	private static final String URI = "http://rtroquete.no-ip.org:8080/WebRest/";
	
	public ArrayList<Treino> getTreinosUsuario(int idAluno) {
		try {
			String json = "";
			URL url = new URL(URI + path + idAluno);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-Type", "application/json");
			
			Gson gson = new Gson();
			
			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
			}
			
			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));
			
			String output;
			while ((output = br.readLine()) != null) {
				json += output;
				System.out.println(output);
			}			
			
			conn.disconnect();
			return gson.fromJson(json, new TypeToken<List<Treino>>(){}.getType());
			
		} catch(Exception e) {
			e.printStackTrace();
		}

		throw new RuntimeException("erro ao recuperar treinos do aluno");
	}

	
}
